;(function() {
  let pageList = [
    {name: '待办工单', path: '/workOrder/todo'},
    {name: '创建工单', path: '/workOrder/create'},
    {name: '我的工单', path: '/workOrder/own'},
    {name: '工单统计', path: '/workOrder/statistics'},
    {name: '工单列表', path: '/workOrder/list'},
    {name: '工单详情', path: '/workOrder/view', props: true},
  ]
  let compomentList = [
    //表单解析
    {name: 'form-parser', path: '/openComponent?is=form-parser'},
  ]
  let getQueryString = (params)=>{
    let urlSearchParams = new URLSearchParams();
    for(let key in params) {
      if(Array.isArray(params[key])) {
        params[key].forEach(item => {
          urlSearchParams.append(key, item)
        })
      } else {
        urlSearchParams.append(key, params[key])
      }
    }
    return urlSearchParams.toString()
  }
  this.CENTER_ORDER = {
    version: '1.0.0',
    install: function(Vue, options) {
      Vue.component('center-order', {
        props: {
          name: { // 页面或者组件名称
            type: String,
            validator: function (value) {
              if(value == undefined) return true
              let f = pageList.find(item => item.name === value)
              if(f) {
                return true
              }
              f = compomentList.find(item => item.name === value)
              if(f) {
                return true
              }else {
                console.error(`center-order: name ${value} not found,name must be one of ${this.names}`)
                return false
              }
            }
          },
          props: { //页面或组件所需要的数据
            type: Object,
            default: () => {}
          },
          width: { // 定义 iframe 的宽度。
            type: String,
            required: false,
            default: () => '100%'
          },
          height: { // 规定 iframe 的高度
            type: String,
            required: false,
            default: () => '100%'
          },
          frameborder: { // 规定是否显示框架周围的边框。
            type: Number,
            required: false,
            default: () => 0
          },
          scrolling: { // 规定是否在 iframe 中显示滚动条。
            type: String,
            required: false,
            default: () => 'auto'
          },
        },
        data() {
          let baseUrl = "https://dsjnlzx.scgsdsj.com:18243/#"
          if(options && options.env === 'production') {
            // TODO,等待环境的地址
            baseUrl = 'http://待定/#'
          }
          return {
            id: 0,
            baseUrl,
            compomentList,
            pageList,
            messageList: []
          }
        },
        watch: {
          name: {
            handler: function (val) {
              if(val.name == '工单详情' && this.props.id === undefined) {
                console.error(`center-order: 工单详情页面需要传工单id, eg,:props="{id: 1}"`)
              }
            },
            immediate: true
          }
        },
        computed: {
          currentItem() {
            let f = this.pageList.find(item => item.name === this.name)
            if(f) {
              return f
            }
            f = this.compomentList.find(item => item.name === this.name)
            if(f) {
              return f
            }
          },
          names(){
            return [...this.pageList.map(item => item.name), ...this.compomentList.map(item => item.name)]
          },
          src() {
            if(this.currentItem){
              let {path} = this.currentItem
              let url = `${this.baseUrl}${path}`
              let params = {...this.props}
              if(this.currentItem.props){
                url += '/'+this.props.id
                delete params.id
              }
              // console.log('params', params)
              if(Object.keys(params).length > 0) {
                const queryString = getQueryString(params);
                if(url.indexOf('?') > -1) {
                  url += `&${queryString}`
                }else{
                  url += `?${queryString}`
                }
              }
              // console.log('url', url)
              return url
            }
          }
        },
        methods: {
          validate() {
            return this.setMessage({method: 'validate'})
          },
          setMessage(data) {
            let id = this.id++
            let p = new Promise((resolve, reject) => {
              this.messageList.push({id, resolve, reject})
            })
            this.$refs.iframeRef.contentWindow.postMessage({ ...data,id}, '*');
            return p
          }
        },
        mounted() {
          window.addEventListener('message', ({data})=>{
            // console.log('父页面接收到消息', data)
            let f = this.messageList.find(item => item.id === data.id)
            if(f){
              f.resolve(data)
              this.messageList = this.messageList.filter(item => item.id !== data.id)
            }
          }, false);
        },
        // template: `
        //   <iframe
        //     ref="iframeRef"
        //     :width="width"
        //     :frameborder="frameborder"
        //     :scrolling="scrolling"
        //     :height="height"
        //     :src="src"
        //     allowfullscreen="allowfullscreen"
        //   />
        // `
        render(createElement) {
          return createElement('iframe',{
            attrs: {
              width: this.width,
              height: this.height,
              frameborder: this.frameborder,
              scrolling: this.scrolling,
              src: this.src,
              allowfullscreen: 'allowfullscreen',
            },
            ref:"iframeRef"
          }, '')
        }
      })
    }
  }
}).call(this);
